package com.village.friend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.StringUtils;
import com.village.friend.dto.request.UserLikeAddDto;
import com.village.friend.dto.request.UserLikeListDto;
import com.village.friend.entity.AppUserLike;
import com.village.friend.entity.User;
import com.village.friend.mapper.AppUserLikeMapper;
import com.village.friend.service.AppUserLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.village.friend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.TreeSet;

/**
 * <p>
 * 用户关注表 服务实现类
 * </p>
 *
 * @author yl
 * @since 2021-09-01
 */
@Service
public class AppUserLikeServiceImpl extends ServiceImpl<AppUserLikeMapper, AppUserLike> implements AppUserLikeService {

    @Autowired
    UserService userService;

    @Override
    public void like(UserLikeAddDto param) {
        QueryWrapper<AppUserLike> qw = new QueryWrapper<>();
        qw.eq("user_id",param.getUsername());
        qw.eq("like_id",param.getLikeUser());

        if(param.getLike() == 0){
            remove(qw);
        }else if(param.getLike() == 1){
            saveOrUpdate(genLike(param.getUsername(),param.getLikeUser()));
        }
    }

    @Override
    public IPage<User> pageByParam(UserLikeListDto param) {

        QueryWrapper<AppUserLike> qw = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(param.getUsername()))
            qw.eq("user_id",param.getUsername());
        IPage<AppUserLike> page = new Page<>(param.getPage(), param.getLimit());
        IPage<AppUserLike> iPage = baseMapper.selectPage(page, qw);

        List<User> users = new ArrayList<>();
        Collection<String> likes = new TreeSet<>();
        if(iPage.getRecords() != null && iPage.getRecords().size() > 0){
            for (AppUserLike like : iPage.getRecords()) {
                likes.add(like.getLikeId());
            }
            users = userService.listIn(likes);
        }


        IPage<User> userIPage = new Page<>();
        userIPage.setTotal(iPage.getTotal());
        userIPage.setPages(iPage.getPages());
        userIPage.setCurrent(iPage.getCurrent());
        userIPage.setSize(iPage.getSize());
        userIPage.setRecords(users);

        return userIPage;
    }

    private AppUserLike genLike(String username, String likeuser){
        AppUserLike like = new AppUserLike();
        like.setUserId(username);
        like.setLikeId(likeuser);
        return like;
    }
}
